package com.example.backend.service;

import com.example.backend.Utils.RobotUtil;
import com.example.backend.dao.AirDao;
import com.example.backend.dao.HumidityDao;
import com.example.backend.dao.TemperatureDao;
import com.example.backend.mapper.po.AirPoExample;
import com.example.backend.mapper.po.HumidityPoExample;
import com.example.backend.mapper.po.TemperaturePoExample;
import com.example.backend.model.SensorData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class AirService {
    private AirDao airDao;

    @Autowired
    public AirService(AirDao airDao) {
        this.airDao = airDao;
    }

    public SensorData getLatestData() {
        AirPoExample example = new AirPoExample();
        List<SensorData> dataList = this.airDao.retrieve(example);
        Optional<SensorData> latestSensorData = dataList.stream()
                .max(Comparator.comparing(SensorData::getTime));
        SensorData sensorData =  latestSensorData.orElseThrow(() -> new RuntimeException("No SensorData available"));
        if(sensorData.getValue() < 48) {
            RobotUtil.sendWarningMessage("空气质量为：" + sensorData.getValue() + "，低于设定范围啦，请及时关注！");
        }
        return sensorData;
    }

    public List<SensorData> getRecentData(Integer duration, String unit) {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = switch (unit) {
            case "sec" -> endTime.minusSeconds(duration);
            case "min" -> endTime.minusMinutes(duration);
            case "hour" -> endTime.minusHours(duration);
            case "day" -> endTime.minusDays(duration);
            case "month" -> endTime.minusMonths(duration);
            case "year" -> endTime.minusYears(duration);
            default -> throw new IllegalArgumentException("Invalid time unit: " + unit);
        };

        AirPoExample example = new AirPoExample();
        List<SensorData> dataList = this.airDao.retrieve(example);

        return dataList.stream()
                .filter(data -> !data.getTime().isBefore(startTime))
                .collect(Collectors.toList());
    }
}
